import FactorAPI from '@/api/Factor';
import { Box, Icon, PaginationTable, PopoverConfirm, SearchFields, useCall, usePaginationCommon } from '@/components';
import { FACTOR_COLUMNS, FACTOR_SEARCH_FIELDS } from '@/constants/sharedFields';
import { forkHandler } from '@/utils';
import { Button, Space } from 'antd';
import React from 'react';
import FactorEditModal from './components/FactorEditModal';

const ACTIONS = {
  edit: {
    dialog: FactorEditModal,
    itemProp: 'item',
    title: '编辑因子',
    text: <Button type='link' icon={<Icon type='edit' />} />,
  },

  del: {
    confirm: '确认删除此因子吗',
    text: <Button type='link' icon={<Icon type='delete' />} />,
  },
};

const FactorPage = () => {
  const { tableRef, searchData, onSearch, onSelect, selectedRef, hasSelected, reset } = usePaginationCommon();

  const onDel = useCall(forkHandler((r) => FactorAPI.remove([r.id]), reset, true));
  const onBatchDel = useCall(forkHandler(() => FactorAPI.remove(selectedRef.current), reset, true));
  const onEdit = useCall(
    forkHandler(
      (r, i, data) =>
        FactorAPI.insertOrUpdate({
          ...data,
          id: r.id,
        }),
      reset,
      true,
    ),
  );
  const onInsert = useCall(forkHandler(FactorAPI.insertOrUpdate, reset, true));

  return (
    <>
      <SearchFields fields={FACTOR_SEARCH_FIELDS} onSubmit={onSearch} onReset={onSearch} />
      <Box flex jus='between' py={2}>
        <Space>
          {hasSelected && (
            <PopoverConfirm content='确认删除已选择的因子吗?' onOk={onBatchDel}>
              <Button>批量删除</Button>
            </PopoverConfirm>
          )}
        </Space>

        <Space>
          <FactorEditModal title='新增因子' onOk={onInsert}>
            <Button>+ 新增</Button>
          </FactorEditModal>
        </Space>
      </Box>
      <PaginationTable
        ref={tableRef}
        service={FactorAPI.findByPage}
        serviceData={searchData}
        columns={FACTOR_COLUMNS}
        actions={ACTIONS}
        actionWidth={100}
        rowSelection={{
          onChange: onSelect,
        }}
        onDel={onDel}
        onEdit={onEdit}
      />
    </>
  );
};

FactorPage.title = '对象及因子配置';

export default FactorPage;
